package com.st.security;

import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration//配置类
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig {

    @Resource
    private SecurityUserServiceImpl securityUserDailService;

    @Resource
    private AccessHandleImpl accessHandle;

    @Resource
    private AuthenticationImpl authentication;

    @Resource
    private SecurityTokenImpl securityToken;

    @Bean
    public PasswordEncoder passwordEncoder(){

        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManager(){
        DaoAuthenticationProvider authenticationProvider =  new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(securityUserDailService);
        ProviderManager pm = new ProviderManager(authenticationProvider);
        return pm;
    }

    //设置放行路径
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http)throws Exception{
        http.authorizeHttpRequests(
                auth -> auth.requestMatchers(HttpMethod.POST,"/user/login").permitAll()
                        //anyRequest除requestMatchers的其他的路径
                        //authenticated让anyRequest匹配的都通过security校验
                        .anyRequest().authenticated()
        );
        http.csrf(csrf -> csrf.disable());

        http.addFilterBefore(securityToken, UsernamePasswordAuthenticationFilter.class);

        http.exceptionHandling().accessDeniedHandler(accessHandle).authenticationEntryPoint(authentication);

        return http.build();
    }

}
